﻿//https://leetcode.cn/problems/merge-intervals/?envType=problem-list-v2&envId=array

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals)
    {
        //按左区间排序
        sort(intervals.begin(), intervals.end());
        //获取第一个区间左右值
        int left = intervals[0][0], right = intervals[0][1];
        //返回结果
        vector<vector<int>> ret;

        for (int i = 1; i < intervals.size(); i++)
        {
            //下一个区间的左右值
            int a = intervals[i][0], b = intervals[i][1];
            if (a <= right)
            {
                //有重叠，合并区间
                right = max(right, b);
            }
            else
            {
                //无重叠，加入结果并更左右区间
                ret.push_back({ left,right });
                left = a;
                right = b;
            }
        }
        //最后一个区间（合并|不合并）
        ret.push_back({ left,right });
        return ret;
    }
};